package com.csair.irp.job.file.parser.base;

import com.csair.irp.job.file.properties.DataFileProperties;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 本地文件管理器
 * 注意路径都不要带斜杠
 *
 * @author liaolonglong
 */
@Component
public class LocalFileManager implements FileManager {

    @Autowired
    private DataFileProperties dataFileProperties;

    @Override
    public void upload(String targetPath, String targetFileName, File srcFile) throws Exception {
        FileUtils.copyFile(srcFile, new File(generatePath(targetPath)));
    }

    @Override
    public File download(String targetPath, String targetFileName, File localParent) throws Exception {
        return download(targetPath, targetFileName, localParent, targetFileName);
    }

    @Override
    public File download(String targetPath, String targetFileName, File localParent, String localFileName) throws Exception {
        File remoteFile = new File(generatePath(targetPath), targetFileName);
        //如果文件不存在就返回null
        if (!remoteFile.exists()) {
            return null;
        }

        File localFile = new File(localParent, localFileName);
        FileUtils.copyFile(remoteFile, localFile);
        return localFile;
    }

    /**
     * 显示某一目录下的所有非隐藏文件
     *
     * @param targetPath 目标文件目录或文件服务器路径
     * @return
     * @throws Exception
     */
    @Override
    public String[] list(String targetPath) throws Exception {
        return new File(generatePath(targetPath)).list((dir, name) -> !name.startsWith("."));
    }

    @Override
    public boolean exists(String targetPath, String... targetFileName) throws Exception {
        File parent = new File(targetPath);
        if (targetFileName.length == 0) {
            return parent.exists();
        }

        List<String> fileNames = Arrays.asList(parent.list());
        for (String temp : targetFileName) {
            if (!fileNames.contains(temp)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void delete(String targetPath, String... targetFileName) throws Exception {
        File parent = new File(targetPath);
        if (targetFileName.length == 0) {
            FileUtils.deleteDirectory(parent);
        }

        for (String temp : targetFileName) {
            FileUtils.forceDelete(new File(parent, temp));
        }
    }

    /**
     * 生成本地文件访问路径，并创建目录
     *
     * @param targetPath
     * @return
     */
    private String generatePath(String targetPath) throws IOException {
        String basePath = dataFileProperties.getFileManager().getBasePath();
        String path = basePath + File.separator + targetPath + File.separator;
        FileUtils.forceMkdir(new File(path));
        return path;
    }
}
